#!/usr/bin/python

from ftplib import FTP
import ftplib
import socket
from smb.SMBConnection import SMBConnection
import requests
from datetime import datetime
import os, shutil

class Myftp:
	def __init__(self, host, port, user, pw):
		self.host = host
		self.port = port
		self.user = user
		self.pw = pw
		self.ftp = FTP()
	def connect(self):
		self.ftp.connect(self.host, self.port)
		self.ftp.login(self.user, self.pw)
	def download_flie(self, remotepath, localpath):
		os.makedirs(os.path.dirname(localpath), exist_ok=True)
		fp = open(localpath, 'wb')
		self.ftp.retrbinary('RETR '+remotepath, fp.write, 1024)
		self.ftp.set_debuglevel(0)
		fp.close()
	def upload_file(self, remotepath, localpath):
		filedir, file = os.path.split(remotepath)
		self.mkdir(filedir)
		fp = open(localpath, "rb")
		self.ftp.storbinary('STOR '+file, fp, 1024)
		self.ftp.set_debuglevel(0)
		fp.close()
	def mkdir(self, path):
		try:
			self.ftp.cwd(path)
		except ftplib.error_perm:
			parent, child = os.path.split(path)
			if parent:
				self.mkdir(parent)
			self.ftp.mkd(child)
			self.ftp.cwd(child)
	def close(self):
		self.ftp.quit()
class Mysmb:
	def __init__(self, host, port, user, pw, service_name):
		self.host = host
		self.port = port
		self.user = user
		self.pw = pw
		self.service_name = service_name
		self.smb = SMBConnection(user, pw, "", "momo", is_direct_tcp=True)
	def connect(self):
		self.smb.connect(self.host, self.port)
	def upload_file(self, remotepath, localpath):
		self.create_directory_recursive(os.path.dirname(remotepath))
		f = open(localpath, "rb")
		self.smb.storeFile(self.service_name, remotepath, f)
		f.close()
	def upload_dir(self, remote_path, local_path):
		"""上传文件夹"""
		for root, dirs, files in os.walk(local_path):
			for file in files:
				local_path = os.path.join(root, file)
				temp = local_path.replace(local_path, '')
				remote_path = remote_path + temp.replace('\\', '/')
				self.upload_file(local_path, remote_path)
	def download_file(self, remotepath, localpath):
		os.makedirs(os.path.dirname(localpath), exist_ok=True)
		f = open(localpath, 'wb')
		self.smb.retrieveFile(self.service_name, remotepath, f)
		f.close()
	def download_directory(self, remote_path, local_path):
		"""递归下载文件夹"""
		for file in self.conn.listPath(self.service_name, remote_path):
			if file.filename.startswith('.'):
				continue
			else:
				if file.isDirectory:
					local_dir = os.sep.join([local_path, file.filename])
					os.makedirs(local_dir, exist_ok=True)
					self.download_directory(os.path.join(remote_path, file.filename), local_dir)
				else:
					local_file = os.sep.join([local_path, file.filename])
					self.download_file(os.path.join(remote_path, file.filename), local_file)
	def is_directory_exists(self, remote_directory):
		filelist = self.smb.listPath(self.service_name, os.path.dirname(remote_directory))
		for file in filelist:
			if file.isDirectory and file.filename == os.path.split(remote_directory)[-1]:
				return True
		return False
	def create_directory_recursive(self, remote_directory):
		"""递归创建文件夹"""
		dirs = remote_directory.strip("/").split("/")
		current_dir = ""
		for directory in dirs:
			current_dir += "/" + directory
			if not self.is_directory_exists(current_dir):
				self.smb.createDirectory(self.service_name, current_dir)
	def close(self):
		self.smb.close()

class Fileinfo:
	def __init__(self, path, word_offset):
		f = open(path, 'rb')
		f.seek(word_offset*4, 0)
		ver = int.from_bytes(f.read(4), byteorder='little', signed=False)
		date = int.from_bytes(f.read(4), byteorder="little", signed=False)
		flag = int.from_bytes(f.read(4), byteorder="little", signed=False)
		crc = int.from_bytes(f.read(4), byteorder="little", signed=False)
		flen = int.from_bytes(f.read(4), byteorder="little", signed=False)
		self.version = 'V{:x}.{:02x}'.format(ver>>16, ver&0xffff)
		self.date = '{:08x}'.format(date)
		self.flag = '0x{:08x}'.format(flag)
		self.crc = '0x{:08x}'.format(crc)
		self.flen = '{:.1f} kB'.format(flen/1024)

		f.close()


# 程序入口
if __name__ == "__main__":
    # 设备型号
	dev_type = 'KT-2043'
	file_type = 'APP'
	# 升级文件发布的本地路径
	local_file = "KT-APP/KT-2043/KT-2043-APP.bin"
	# 升级文件发布的FTP位置
	ftp_file = "KT-APP/KT-2043/KT-2043-APP.bin"
	# 群机器人 webhook
	webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=cb87cb69-8de1-4fdd-b89e-5b2716c334fd"

	# 创建FTP对象
	ftp = Myftp('iot.ktzhypt.com', 5021, 'administrator', 'Kt01212019')
	ftp.connect()
	# 从本地传文件到服务器 第一参数服务器 第二参数本地
	ftp.upload_file(ftp_file, local_file)
	ftp.close()
	print('FTP发布成功')
	
	# 本地发布到本地文件夹
	# 读取文件信息，版本、大小等
	info = Fileinfo(local_file, 98)
	release_path = 'release/' + dev_type + '-' + file_type + info.version + '.' + info.date[4:] + '-GUIv1.02' + '-' + info.date + '/' + local_file
	os.makedirs(os.path.dirname(release_path), exist_ok=True)
	print('本地发布路径:' + release_path)
	shutil.copy(local_file, release_path)
	print('本地发布成功')
	
	
	# 创建SMB对象
	smb = Mysmb('smb.ktzhypt.com', 445, 'Shared', '01212019', 'A程序文件')
	smb.connect()
	# 从本地传文件到服务器 第一参数服务器 第二参数本地
	smb.upload_file("/KT-2043/设备程序/程序说明.html", "程序说明.html")
	smb.upload_file("/KT-2043/设备程序/" + release_path[8:], local_file)
	smb.close()
	print("SMB发布成功")
	

	# 发送企业微信消息
	message = '# '+dev_type+'    '+file_type+'\n' + datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'\n'
	message = message+'<font color="info">' +info.version+'.'+info.date[4:]+'        '+info.flen+'</font>\n'
	while True:
		in_msg = input("输入企业微信消息:\n")
		if len(in_msg) == 0:
			break
		message = message + in_msg + '\n'
	print(message)
	markdown = {}
	markdown['content'] = message
	
	body = {}
	body['msgtype'] = 'markdown'
	body['markdown'] = markdown
	print(body)

	header = {"Content-Type":"application/json"}
	r = requests.post(webhook, json=body, headers=header)
	print(r.text)
	print("回车结束")
	input()
